﻿// -----------------------------------------------------------------------
// <copyright file="Serializer.cs" company="SureKAM">
// Copyright (c) SureKAM. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Omes.Services
{
    /// <summary>
    /// 序列化器
    /// </summary>
    public static class Serializer
    {

        /// <summary>
        /// JSON序列化
        /// </summary>
        /// <typeparam name="T"/>需要序列化的类< peparam/>
        /// <param name="t">需要序列化的对象</param>
        /// <returns>序列化后的Json字符串</returns>
        public static string JsonSerializer<T>(T t)
        {
            try
            {
                var ser = new DataContractJsonSerializer(typeof(T));
                var ms = new MemoryStream();
                ser.WriteObject(ms, t);
                string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return jsonString;
            }
            catch (Exception err)
            {
               // ErrorManager.ShowError(err.Message);
                return string.Empty;
            }
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// <typeparam name="T">需要反序列化的类</typeparam>
        /// <param name="jsonString">序列化后的Json字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T JsonDeserialize<T>(string jsonString) where T : new()
        {
            try
            {
                var ser = new DataContractJsonSerializer(typeof(T));
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                var obj = (T)ser.ReadObject(ms);
                return obj;

            }
            catch (Exception err)
            {
                return new T();
            }
        }


    }
}
